from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request

from info import constants, db
from info.models import News, Comment, CommentLike, User
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu

@news_blu.route('/followed_user',methods = ['POST'])
@user_login_data
def followed_user():
    if not g.user:
        return jsonify(errno = RET.SESSIONERR,errmsg = '用户未登录')

    user_id = request.json.get('user_id')
    action = request.json.get('action')
    if not all([user_id,action]):
        return jsonify(errno=RET.PARAMERR,errmsg = '参数不足')
    if action not in ('follow','unfollow'):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询错误')

    if not target_user:
        return jsonify(errno = RET.NODATA,errmsg = '未查询到作者信息')

    if action == 'follow':
        if target_user.followers.filter(User.id == g.user.id).count()>0:
            return jsonify(errno = RET.DATAEXIST,errmsg = '当前已关注')
        target_user.followers.append(g.user)
    else:
        if target_user.followers.filter(User.id == g.user.id).count()>0:
            target_user.followers.remove(g.user)


    return jsonify(errno=RET.OK,errmsg = '操作成功')


@news_blu.route('/comment_like',methods = ['POST'])
@user_login_data
def set_comment_like():
    # 评论点赞功能
    # 获取参数:comment_id,action
    user = g.user
    if not g.user:
        return jsonify(errno=RET.SESSIONERR,errmsg = '用户未登录')

    comment_id = request.json.get('comment_id')
    action = request.json.get('action')

    if not all([comment_id,action]):
        return jsonify(errno = RET.PARAMERR,errmsg = '参数不足')

    if action not in ['add','remove']:
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    try:
        comment_id = int(comment_id)
    except Exception as  e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    try:
        comment = Comment.query.get(comment_id)
    except Exception as  e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DATAERR,errmsg = '数据查询失败')

    if not comment:
        return jsonify(errno = RET.NODATA,errmsg = '评论不存在')

    if action == 'add':
        comment_like_model = CommentLike.query.filter(CommentLike.user_id == user.id,CommentLike.comment_id == comment.id).first()
        if not comment_like_model:
            comment_like_model = CommentLike()
            comment_like_model.user_id = user.id
            comment_like_model.comment_id = comment.id
            db.session.add(comment_like_model)
            comment.like_count += 1
    else:
        comment_like_model = CommentLike.query.filter(CommentLike.user_id == user.id,CommentLike.comment_id == comment.id).first()
        if comment_like_model:
            db.session.delete(comment_like_model)
            comment.like_count -= 1
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno = RET.BDERR,errmsg = '数据库操作失败')

    return jsonify(errno = RET.OK,errmsg = 'OK')


@news_blu.route('/news_collect',methods = ['POST'])
@user_login_data
def news_collect():
    # 用户收藏和取消收藏功能实现
    # 接受参数action 和 news_id
    # 1.判断用户是否登录
    # 2.登录了,就判断用户进行的操作,收藏就将相应的数据存到数据库
    # 3.没有登录就提示用户该登录
    user = g.user
    params = request.json
    news_id = params.get('news_id')
    action = params.get('action')
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')

    if not all([news_id,action]):
        return jsonify(errno = RET.PARAMERR,errmsg ='参数不足')



    if action not in ['collect','cancel_collect']:
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    try :
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询错误')

    if not news:
        return jsonify(errno = RET.NODATA,errmsg = '新闻数据不存在')

    if action == 'collect':
        # 实现收藏操作
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        # 实现取消收藏操作
        if news in user.collection_news:
            user.collection_news.remove(news)

    return jsonify(errno=RET.OK,errmsg = '操作成功')

@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):

    # 实现新闻详情页内容展示
    # 需要获取新闻数据,用户数据
    # 将数据随模板带回
    # 1.页面新闻详情展示
    try:
        new = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not new:
       abort(404)

    new.clicks += 1



    # 2.详情页排行榜数据
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)

    except Exception as e:
        current_app.logger.error(e)

    clicks_news_list = []
    for news in news_list if news_list else None:
        clicks_news_list.append(news.to_basic_dict())

    # 3.用户收藏的显示和隐藏

    # 4.评论显示
    comments = None
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)


    # 5.点赞显示
    is_collected = False
    is_followed = False
    comment_like_ids = []
    if g.user:
        try:
            if new in g.user.collection_news:
                is_collected = True

            if news.user.followers.filter(User.id == g.user.id).count() > 0:
                is_followed = True

            comment_ids = [comment.id for comment in comments]
            if len(comment_ids)>0:
                # 用户在该新闻下所有的点赞评论
                comment_likes = CommentLike.query.filter(CommentLike.user_id ==g.user.id ,CommentLike.comment_id.in_(comment_ids)).all()
                # 取出记录中所有点赞评论的comment_id
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)

    comment_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict['is_like'] = False
        if comment.id in comment_like_ids:
            comment_dict['is_like'] = True

        comment_list.append(comment_dict)


    data = {
            'click_news_list': clicks_news_list,
            'news': new.to_dict(),
            'user_info': g.user.to_dict() if g.user else None,
            'is_collected':is_collected,
            'comment':comment_list,
            'is_followed':is_followed
        }

    return render_template('news/detail.html',data = data)

@news_blu.route('/news_comment',methods = ['POST'])
@user_login_data
def add_news_comment():

    params = request.json
    news_id = params.get('news_id')
    comment_content =params.get('comment')
    parent_id = params.get("parent_id")

    if not g.user:
        return jsonify(errno = RET.SESSIONERR,errmsg = '请登录')

    if not all([news_id,comment_content]):
        return jsonify(errno = RET.DATAERR,errmsg = '参数不足')

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception  as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.PARAMERR,errmsg = '参数错误')

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR,errmsg = '查询错误')

    if not news:
        return jsonify(errno=RET.NODATA,errmsg = '为查询到新闻数据')

    comment = Comment()
    comment.user_id = g.user.id
    comment.news_id = news_id
    comment.content = comment_content

    if parent_id:
        comment.parent_id = parent_id

    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback

    return jsonify(errno = RET.OK,errmsg = "OK",data = comment.to_dict())
